package com.iweb.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.iweb.common.result.EmptyObject;
import com.iweb.common.result.ResultEntity;
import com.iweb.config.ServerConfig;
import com.iweb.model.ImageFile;
import com.iweb.service.ImageService;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

@RestController
@RequestMapping("image")
public class ImageController {

    @Autowired
    private ImageService imageService;

    @Autowired
    private ServerConfig serverConfig;

    @SneakyThrows
    @ApiOperation("保存图片，返回url")
    @PostMapping("{pos}")
    public ResultEntity<ImageFile> saveImage(@RequestParam("file") MultipartFile file,
                                             @PathVariable Long pos) {
        ImageFile imageFile = new ImageFile();
        // 设置id
        imageFile.setId(IdWorker.getIdStr());
        // 设置文件名称
        imageFile.setName(file.getOriginalFilename());
        // 设置文件类型
        imageFile.setContentType(file.getContentType());
        // 设置上传时间
        imageFile.setUploadTime(LocalDateTime.now());
        // 设置文件大小
        imageFile.setSize(file.getSize());
        // 设置图片在文本中的位置
        imageFile.setPos(pos);
        // 设置文件内容
        imageFile.setContent(new Binary(StreamUtils.copyToByteArray(file.getInputStream())));
        // 设置返回的url
        imageFile.setUrl(String.format(serverConfig.getUrl() + "/image/%s", imageFile.getId()));
        // 保存图片
        imageService.saveFile(imageFile);
        return ResultEntity.SUCCESS(imageFile);
    }

    @ApiOperation("获取图片")
    @GetMapping(value = "{id}", produces = {MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE})
    public byte[] getImage(@PathVariable String id) {
        ImageFile file = imageService.getFileById(id);
        return file.getContent().getData();
    }

    @ApiOperation("删除图片")
    @DeleteMapping("{id}")
    public ResultEntity<EmptyObject> deleteImage(@PathVariable String id) {
        imageService.removeFile(id);
        return ResultEntity.SUCCESS();
    }

}
